package com.keur.money.ui.main.fm

import android.annotation.SuppressLint
import android.view.LayoutInflater
import android.view.View
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.GridLayoutManager
import com.keur.money.R
import com.keur.money.app.MyApp
import com.keur.money.base.adapter.MullaOnItemChildClickListener
import com.keur.money.base.utils.DensityUtils
import com.keur.money.base.utils.TitleBarUtil
import com.keur.money.databinding.FmMullaCouponBinding
import com.keur.money.http.ApiService
import com.keur.money.http.ApiService.addCommonParams
import com.keur.money.http.ApiService.addRandomParams
import com.keur.money.http.HttpHelper
import com.keur.money.http.IHttpCallback
import com.keur.money.mvp.ProFm
import com.keur.money.ui.main.adapter.KeurCouponAdapter
import com.keur.money.ui.user.act.KeurUserCouponAct
import com.keur.money.ui.user.act.KeurUserLuckyDrawAct
import com.keur.money.ui.user.act.KeurUserMessageAct
import com.keur.money.ui.user.act.KeurUserPointsAct
import com.keur.money.ui.user.act.KeurUserVipAct
import com.keur.money.utils.DateUtils
import com.keur.money.utils.decoration.GridSpacingItemDecoration
import com.keur.money.utils.dialog.CouponExchangeDialog
import com.keur.money.utils.dialog.TipsDialog
import com.keur.money.utils.event.KeurEventData
import com.keur.money.utils.event.KeurEventType
import com.keur.money.utils.helper.KeurCustomConfigsHelper
import com.keur.money.utils.helper.SharedHelper
import org.json.JSONObject

/**
 * MullaFlow
 * @Author wwdeng
 * @CreateTime: 2024/7/26 16:57
 * @Annotation：优惠券
 */
class KeurCouponFm: ProFm() {
    private var _binding: FmMullaCouponBinding? = null
    private val binding get() = _binding ?: throw IllegalStateException(
        "Cannot access binding because it is null. Either the view hasn't been created yet, or it has already been destroyed."
    )

    private var couponAdapter: KeurCouponAdapter? = null

    override fun getMullaRootView(inflater: LayoutInflater): View {
        _binding = FmMullaCouponBinding.inflate(inflater)
        return binding.root
    }

    override fun initMullaView() {
        _binding?.parentLayout?.setPadding(0, TitleBarUtil.getStatusBarHeight(), 0, 0)
        initMullaRefreshLayout()
        initMullaRecyclerView()
    }

    override fun initMullaListener() {
        //客服
        _binding?.imgKefu?.setOnClickListener {
            showMullaKefuDialog("Coupon Page")
            HttpHelper.addKeurEventAction(KeurEventType.CLICK.KEUR_CLICK_CUSTOMER,"Coupon Page")
        }

        //消息
        _binding?.imgMessage?.setOnClickListener {
            onIntent(KeurUserMessageAct::class.java)
        }

        //优惠券列表
        _binding?.couponLayout?.setOnClickListener {
            onIntent(KeurUserCouponAct::class.java)
        }
        //积分明细
        _binding?.pointsLayout?.setOnClickListener {
            onIntent(KeurUserPointsAct::class.java)
        }
        //抽奖中心
        _binding?.pointsDrawLayout?.setOnClickListener {
            onIntent(KeurUserLuckyDrawAct::class.java)
        }

    }

    override fun initMullaData() {
        _binding?.textUserPoints?.text = getMullaUserPoints().toString()
        couponAdapter?.data = KeurCustomConfigsHelper.getMullaCouponList()

        //牌照信息
        val licenseInfo = KeurCustomConfigsHelper.getMullaLicenseInfo()
        if (licenseInfo == null){
            _binding?.licenseLayout?.removeAllViews()
            _binding?.licenseLayout?.visibility = View.GONE
        } else {
            _binding?.licenseLayout?.removeAllViews()
            _binding?.licenseLayout?.addView(licenseView())
            _binding?.licenseLayout?.visibility = View.VISIBLE
        }
        HttpHelper.addKeurEventAction(KeurEventType.PAGE.KEUR_PAGE_COUPON_CENTER_START)
    }

    /* 初始化刷新 */
    private fun initMullaRefreshLayout() {
        //禁止加载
        _binding?.refreshLayout?.setEnableLoadMore(false)
        _binding?.refreshLayout?.setEnableAutoLoadMore(false)
        _binding?.refreshLayout?.setOnRefreshListener {
            initMullaData()
            _binding?.refreshLayout?.finishRefresh()
        }
        _binding?.refreshLayout?.setOnLoadMoreListener {
            _binding?.refreshLayout?.finishLoadMore()
        }
    }

    /**
     * 初始化优惠券列表
     */
    private fun initMullaRecyclerView() {
//        _binding?.recyclerView.setHasFixedSize(true)
//        _binding?.recyclerView.isNestedScrollingEnabled = false
//        _binding?.recyclerView.isFocusableInTouchMode = false //不需要焦点
        val topDecoration = DensityUtils.dp2px(16f)
        _binding?.recyclerView?.addItemDecoration(GridSpacingItemDecoration(2, topDecoration, false))
        _binding?.recyclerView?.layoutManager = GridLayoutManager(context,2)
        couponAdapter = KeurCouponAdapter(_binding?.recyclerView)
        couponAdapter?.userPoints = getMullaUserPoints()
        _binding?.recyclerView?.adapter = couponAdapter
        _binding?.recyclerView?.itemAnimator = DefaultItemAnimator()
        couponAdapter?.setOnItemChildClickListener(MullaOnItemChildClickListener { _, childView, position ->
            val item = couponAdapter?.getItem(position)
            item?.let {
                val isExchange = it.optBoolean("isExchange", false)
                when (childView.id) {
                    R.id.itemLayout -> {//点击Item
                        //不可兑换 - 进入VIP等级中心
                        if (!isExchange) {
                            KeurUserVipAct.start(requireContext(),getMullaUserVip())
                        }
                    }

                    R.id.btnExchange -> {//兑换
                        //可兑换
                        if (isExchange && getMullaUserPoints() >= it.optInt("score")) {
                            showMullaCouponExchangeDialog(it)
                        }
                    }
                }
            }
        })
    }

    /**
     * 兑换优惠券信息预览
     */
    private fun showMullaCouponExchangeDialog(item: JSONObject){
        val exchangeDialog = CouponExchangeDialog(context,object : CouponExchangeDialog.IDialogCallback{
            override fun onMullaExchangeAction(couponInfo: JSONObject?) {
                couponInfo?.let {
                    showMullaCouponExchangeSureDialog(it)
                }
            }
        })
        exchangeDialog.show()
        exchangeDialog.setMullaCouponInfo(item)
    }

    /**
     * 兑换优惠券确认
     */
    private fun showMullaCouponExchangeSureDialog(couponInfo: JSONObject){
        val showTipsText = String.format(getString(R.string.coupon_exchange_dialog_sure_tips),"${couponInfo.optString("score")} ${couponInfo.optString("currency")}")
        val tipsDialog = TipsDialog(context,object : TipsDialog.IDialogCallback{
            override fun onClick(view: View?) {
                if (view?.id == R.id.btnOk){
                    onMullaExchangeCouponAction(couponInfo)
                }
            }
        })
        tipsDialog.setCancelable(true)
        tipsDialog.setCanceledOnTouchOutside(false)
        tipsDialog.show()
        tipsDialog.setTipsTitle("")
        tipsDialog.setTips(showTipsText)
        tipsDialog.setBtnText(getString(R.string.btn_sure))
    }

    @SuppressLint("NotifyDataSetChanged")
    override fun onKeurEvent(event: KeurEventData) {
        when(event.eventType){
            KeurEventData.TYPE.KEUR_POINTS_REFRESHED -> {
                //刷新积分完成
                _binding?.textUserPoints?.text = getMullaUserPoints().toString()
                //更新积分，刷新可兑换优惠券列表
                couponAdapter?.userPoints = getMullaUserPoints()
                couponAdapter?.notifyDataSetChanged()
            }
            KeurEventData.TYPE.KEUR_COUPON_REFRESHED -> {
                //刷新优惠券完成
                _binding?.textCouponCount?.text = getMullaUserCouponCount().toString()
            }
            else -> {

            }
        }
    }

    /**
     * 兑换优惠券
     */
    private fun onMullaExchangeCouponAction(couponInfo: JSONObject){
        showMullaLoading(isTOuchOut = false, isCancel = true)
        val httpUrl = ApiService.getHttpUrl(ApiService.API_PATH.KEUR_API_SAVE_OR_USE_PATH)
        val params = JSONObject().addCommonParams().addRandomParams().apply {
            put("mobile", SharedHelper.getKeurSPString(SharedHelper.KEUR_SPKEY.KEUR_MOBILE))
            put("scoreUseType","scoreToCoupon")//积分兑换优惠券
            put("scoreUseInfo",getString(R.string.points_use_info_exchange_coupon))//分数使用说明
            put("score","-${couponInfo.optString("score")}")//分数变化值 增加传正数，减少传负数
            put("couponInfo",couponInfo.toString())//优惠券信息
            put("amount",couponInfo.optString("amount"))//优惠券金额
            put("expirationTime", DateUtils.getTwoMonthsLaterTimestamp() / 1000)//优惠券失效时间戳(秒) : 2个月后
        }
        HttpHelper.postKeurAction(httpUrl,params,object : IHttpCallback {
            override fun onRequestSuccess(data: JSONObject) {
                showMullaToast(data.optString("msg"))
                when(data.optInt("code")) {
                    0 -> {//成功
                        val obj = data.optJSONObject("obj")

                        //刷新积分
                        MyApp.app.publisher.publish(KeurEventData(KeurEventData.TYPE.KEUR_POINTS_REFRESH))
                    }
                }
            }

            override fun onRequestError(error: JSONObject) {
                showMullaToast(error.optString("errorMsg"))
            }

            override fun onRequestFinish() {
                hideMullaLoading()
            }
        })
    }

    override fun onDestroy() {
        super.onDestroy()
        HttpHelper.addKeurEventAction(KeurEventType.PAGE.KEUR_PAGE_COUPON_CENTER_END)
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
}